from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

# 初始化 SQLAlchemy
db = SQLAlchemy()


def create_app():
    app = Flask(__name__)

    # 配置数据库连接
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or \
                                            'mysql://{user}:{password}@{host}:{port}/{db}'.format(
                                                user=os.environ.get('DB_USER', 'root'),
                                                password=os.environ.get('DB_PASSWORD', '123456'),
                                                host=os.environ.get('DB_HOST', 'localhost'),
                                                port=os.environ.get('DB_PORT', '3306'),
                                                db=os.environ.get('DB_NAME', 'python-web-study'),
                                            )
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # 初始化数据库
    db.init_app(app)

    from .routes import main
    app.register_blueprint(main)

    return app


app = create_app()

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)